
let db = require('../utils/DB');//数据库
let to = require('../utils/await-to-js');
let { SUCCESS, ERROR } = require('../utils/result');//结果
let { HOST } = require('../utils/CONSTANT');//常量模块
const jwt = require('../utils/jwt');

//查询购物车
function selectModel() {
    return async (req, res) => {
        // let [err, data] = await to(db.query(`SELECT * FROM category_first`, [HOST]));
        // err ? ERROR(res, '一级分类查询失败', err) : SUCCESS(res, data);
        // SUCCESS(res, { msg: "成功的经过登录拦截，进入购物车模块" });
        let { token } = req.query;
        let playload = token.split('.')[1];//base64格式的荷载
        let { uid } = jwt.base64ToJson(playload);//将base64格式的playload转换为对象，解析UID
        let [err, data] = await to(getShopcarData(uid));//获取登录用户的购物车
        if (err) {
            ERROR(res, '查询购物车错误', err);
            return;
        }
        let arr = [];//保存返回给客户端的数据
        //遍历购物车数据源，为每一个购物车数据添加styleList属性
        for (let item of data) {            
            let stylObj = JSON.parse(item.style_obj)[0];//将字符串转换为对象(数组)
            let styleValue = await getStyleValue(stylObj['style_value_id']);//数组
            let styleName = await getStyleName(stylObj['style_name_id']);//数组
            // console.log(styleValue);
            // console.log(styleName);
            item.styleList = [{
                "style_value_id": styleValue[0]['style_value'],
                "style_name_id": styleName[0]['style_name']
            }];
            console.log(item);
            arr.push(item);
        };
        SUCCESS(res, arr);
    };
}

//获取购物车数据
function getShopcarData(id) {
    return db.query(`SELECT a.id,a.goods_id,a.goods_num,a.style_obj,b.goods_name,b.goods_price,b.assem_price,b.image_url FROM shopcar as a
    LEFT JOIN goods_list as b ON a.goods_id=b.goods_id WHERE uid=?`, [id]);
}

//-- 根据style_value_id获取style_value
function getStyleValue(id) {
    return db.query(`SELECT style_value FROM goods_style WHERE style_value_id=?`, [id]);
}

//-- 根据style_name_id获取style_name
function getStyleName(id) {
    return db.query(`SELECT style_name FROM goods_style WHERE style_name_id=?`, [id]);
}


module.exports = selectModel;